#include <sstream>
#include <iostream>
#include <wiringPi.h>
#include "globals.h"
#include "HPCSensor.h"

using namespace std;

HPCSensor::HPCSensor( unsigned long id, unsigned int pin )
    : m_ID(id), m_Pin(pin), m_FireAlways(false), m_Value(), m_Old()
{
    PROFILE_THIS;
    pinMode( m_Pin, INPUT );
}

HPCSensor::~HPCSensor()
{
    PROFILE_THIS;
    if ( m_OnChangeHandle.connected() )
    {
        m_OnChangeHandle.disconnect();
    }
    if ( m_OnAlarmHandle.connected() )
    {
        m_OnAlarmHandle.disconnect();
    }
}

HPCSensor& HPCSensor::FireAlways( bool on )
{
    PROFILE_THIS;
    m_FireAlways = on;
    return *this;
}

string HPCSensor::asString() const
{
    PROFILE_THIS;
    stringstream s;
    s << "Sensor " << Name() << " (Type " << (unsigned int)Type() << ", ID " << ID() << ") on pin " << Pin();
    return s.str();
}

void HPCSensor::addAlarm( const char* Min, const char* Max )
{
    PROFILE_THIS;
    m_Value.addAlarm( Min,Max );
}

void HPCSensor::OnChange( const TSignalChange::slot_type &subscriber )
{
    PROFILE_THIS;
    if ( !m_OnChangeHandle.connected() )
    {
        m_OnChangeHandle = m_OnChange.connect( subscriber );
    }
    else
    {
        LOG( warning, Name() << ": already connected to an OnChange-eventhandler!" );
    }
}

void HPCSensor::OnAlarm( const TSignalAlarm::slot_type &subscriber )
{
    PROFILE_THIS;
    if ( !m_OnAlarmHandle.connected() )
    {
        m_OnAlarmHandle = m_OnAlarm.connect( subscriber );
    }
    else
    {
        LOG( warning, Name() << ": already connected to an OnAlarm-eventhandler!" );
    }
}
